package com.example.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.*;
import com.example.demo.mapper.GoodsMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

@RestController
@RequestMapping("/goods")
public class GoodsController extends BaseController {

    @Resource
    GoodsMapper goodsMapper;

    @PostMapping
    public Result<?> save(@RequestBody Goods goods) {
        goods.setCreateTime(new Date());
        return Result.success(goodsMapper.insert(goods));
    }

    @PutMapping
    public Result<?> update(@RequestBody Goods goods) {
        return Result.success(goodsMapper.updateById(goods));
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        return Result.success(goodsMapper.deleteById(id));
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id) {
        return Result.success(goodsMapper.getById(id));
    }

    @GetMapping("/all")
    public Result<?> findAll() {
        return Result.success(goodsMapper.selectList(null));
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String title,
                              @RequestParam(defaultValue = "") Long categoryId) {
        Page<Goods> page = goodsMapper.findPage(new Page<>(pageNum, pageSize), title, categoryId);
        return Result.success(page);
    }

}
